package com.fengzan.hadoop.socket.client;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;


public class SocketClient {


    /**
     * 初始化选择器
     */
    private Selector selector;

    /**
     * 初始化网络通道
     */
    private SocketChannel socketChannel;



    public SocketClient(String host, int port) {
        connectServer(host, port);
    }

    private void connectServer(String host, int port){
        try {
            //获取选择器
            selector = Selector.open();
            //获取服务器网络地址
            InetSocketAddress inetSocketAddress = new InetSocketAddress(host, port);
            //获取网络通道
            socketChannel = SocketChannel.open(inetSocketAddress);
            //设置网络通道非阻塞
            socketChannel.configureBlocking(false);
            //将网络通道注册到选择器
            socketChannel.register(selector, SelectionKey.OP_READ);
            sendInfo("connect server");
        }catch(ConnectException ce){
            ce.printStackTrace();
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            connectServer(host, port);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 向服务器发送信息
     *
     * @param message
     */
    public void sendInfo(String message) {
        try {
            //向通道写入数据
            socketChannel.write(ByteBuffer.wrap(message.getBytes(StandardCharsets.UTF_8)));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 读取服务器发来的信息
     */
    public void readInfo() {
        try {
            //获取请求数
            int count = selector.select();
            if (count > 0) {
                //获取请求集
                Iterator<SelectionKey> selectionKeyIterator = selector.selectedKeys().iterator();
                //遍历请求集
                while (selectionKeyIterator.hasNext()) {
                    //获取请求
                    SelectionKey selectionKey = selectionKeyIterator.next();
                    //判断位读请求
                    if (selectionKey.isReadable()) {
                        //获取通道
                        SocketChannel sc = (SocketChannel) selectionKey.channel();
                        //创建缓冲区
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        //读取通道的数据到缓冲区
                        sc.read(byteBuffer);
                        //缓冲区数据转字符串
                        String message = new String(byteBuffer.array());
                        //输出
                        System.out.println(message.trim());
                    }
                    //移除已完成请求
                    selectionKeyIterator.remove();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

/*
    public static void main(String[] args) {
        SocketClient groupChatClient = new SocketClient("localhost",6666);
        *//**
         * 开启一个线程，每3秒读取一次服务器发来的信息
         *//*
        new Thread() {
            @Override
            public void run() {
                while (true) {
                    groupChatClient.readInfo();
                    try {
                        Thread.sleep(1000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
        //信息输入
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入信息：");
        while (scanner.hasNextLine()) {
            String s = scanner.nextLine();
            //信息发送
            groupChatClient.sendInfo(s);
            System.out.println("请输入信息：");
        }
    }*/
}